import json
import time
from typing import Dict, List, Any, Optional
from dataclasses import dataclass
from datetime import datetime

import requests
from numpy import random

from app.modules1.PublicApproach import get_token_result, get_last_month_range, _get_vendor_ids_from_db
from app.modules1.common.encryptionUtils import getResult1
from config import DB


@dataclass
class PurchaseDataSummary:
    """采购数据汇总信息"""
    total_records: int
    total_amount: float
    total_quantity: float
    vendor_count: int
    goods_count: int
    date_range: tuple
    goods_details: List[Dict[str, Any]]  # 所有货品详情
    purchaser_details: List[Dict[str, Any]]  # 采购员详情
    vendor_details: Dict[str, Dict[str, Any]]  # 供应商详情（保留用于兼容）


class RealSalesDataAnalyzer:
    """实销数据分析器"""

    def __init__(self):
        self.base_url = "https://web.jackyun.com/jkyun/erp/purchorder/getpurchoutinwarehouseinfo"
        self.base_headers = {
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            "module_code": "mainframe",
            "origin": "https://web.jackyun.com",
            "referer": "https://web.jackyun.com/home/mainframe_web.html",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "Windows",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.125 Safari/537.36",
            "x-requested-with": "XMLHttpRequest",
        }
        # 排除一件代发仓的仓库ID列表
        self.warehouse_ids = "1336070890133324544,743255118019625856,743255118128677760,1417239991126099712,1986443614567170560,2068841910925919232,1920407559764902400,1964561067655692800,2208016583559939456,2202392778890937856,2200186645209351040,2200186641166041984,2200186632039236480,2200186636594250624,2200186627115123584,2200186620437791616,2200186612082738048,2200186603778016128,2187742358607823104,2187694686379836544,2181416842340533888,2181416325770053248,2173325962101293952,2170479451046217472,2170432319370724608,2170307271536740096,2158943111372244224,2158942078266836096,2158930682542195968,2158927911986300160,2148746470579437824,2128314708271105792,2124676649520923776,2122534243312797696,2122494971476248192,2120649486729381120,2112540702796873984,2109664993634814464,2103041129078129920,2101003695678195072,2099523790783284608,2093503182696286080,2092786234173489920,2092039419363264256,2091497826654815232,2087076535149167360,2083500816324167040,2083500466602148992,2083498984839774592,2082738907052311936,2082107296143705344,2081232078274200064,2073928802906276608,2073406285774981120,2071923154067817088,2069089932444338048,2068254008513725056,2064942437610357248,2060854904866374144,2058939255752558464,2056569698050279552,2048636352525961472,2048094649792529024,2047317693519792128,2043443863122937728,2039289456388540288,2039200520004863872,2037735172584833408,2036967797411448704,2032594137851495296,2030767087823292288,2029400904921155072,2029200573546170112,2029173442505246208,2029125719866672000,2028417987521609984,2026920165257315968,2026303999190107008,2023963651698001536,2018222206859740160,2017836176524575744,2017438930167531392,2016159862624256896,2015228285811589376,2014630275881797376,2012823398366642688,2012819020383682816,2005407668229768320,2005396093774660224,2004663147954080000,2002168044857919872,1992969049087017600,1989986473105098880,1987813258947789056,1986448481069106304,1986445822683677184,1985680223205458688,1984253834350723968,1977098091512071296,1970325698298316032,1967424274042127232,1967398617954321280,1967371151917515136,1966734138831406208,1955858059988207488,1955064187267745664,1950827615111807744,1947206852520313984,1946558060365153536,1942127174206949632,1940604795937293184,1938499502388184576,1921679199118885504,1921678607822684800,1921678013380756096,1921676447070880000,1737602652568126976,1633949968465756800,1627522238705140992,1194223064054530432"

    def fetch_purchase_data(self,
                            vendor_types: str = "实销实结,OEM实销实结",
                            page_size: int = 1000,
                            max_pages: Optional[int] = None) -> List[Dict[str, Any]]:
        """获取采购出入库明细数据
        
        Args:
            vendor_types: 供应商类型，默认为"实销实结、OEM实销实结"
            page_size: 每页数据量，默认1000
            max_pages: 最大页数限制，None表示获取全部
            
        Returns:
            采购明细数据列表
        """
        print(f"[INFO] 开始获取采购出入库明细数据，供应商类型: {vendor_types}")

        # 获取认证信息
        token = get_token_result()
        if not token:
            raise ValueError("无法获取有效的认证token")
        print(f"[INFO] 获取到token: {token[:20]}...")

        # 获取时间范围
        start_date, end_date = get_last_month_range()
        print(f"[INFO] 查询日期范围: {start_date} 到 {end_date}")

        # 获取供应商ID
        vendor_ids_str = _get_vendor_ids_from_db(vendor_types)
        print(f"[INFO] 获取到供应商ID: {vendor_ids_str}")

        all_data = []
        page_index = 0
        session = requests.Session()

        try:
            while True:
                if max_pages and page_index >= max_pages:
                    print(f"[INFO] 达到最大页数限制: {max_pages}")
                    break

                # 构建请求头
                headers = self.base_headers.copy()
                headers["authorization"] = f"Bearer {token}"

                # 构建请求数据
                data_payload = {
                    "getType": "1",
                    "billNos": "",
                    "queryDateType": "2",
                    "timeType": "3",
                    "startTime": start_date,
                    "endTime": end_date,
                    "isQuickSearch": "0",
                    "inouttype": "",
                    "skuIds": "",
                    "brandId": "",
                    "vendIds": str(vendor_ids_str),
                    "cateIds": "",
                    "warehouseIds": self.warehouse_ids,
                    "companyId": "1924002902255536000",  # 新疆最西域电子商务有限公司
                    "settStatus": "",
                    "paidStatus": "",
                    "applyUserName": "",
                    "busiName": "",
                    "purchOfficeName": "",
                    "memo": "",
                    "isHideWriteOffBill": "0",
                    "archived": "0",
                    "pageIndex": str(page_index),
                    "pageSize": str(page_size),
                    "sortField": "",
                    "sortOrder": "",
                    "cols": '["goodsdocNo","trDate","orderDate","vendId","vendName","orderNum","goodsNo","goodsName","skuName","quantity","taxPrice","payableAmount","unitName","currencyName","abbreviation","currencyRate","vendOrderId","recDate","isCertified","noTaxPrice","noTaxAmount","taxAmount","settStatus","paidStatus","batchNo","serialNo","companyName","orderCompanyName","purchOfficeName","busiName","applyUserName","comment","rowRemark","inOutMemo","orderMemo","orderDetailRemark","warehouseName","cateName","brandName","skuBarcode","inouttype"]',
                }

                # 发送请求
                requests_data = getResult1(token, data_payload)
                response = session.post(
                    self.base_url,
                    headers=headers,
                    data=requests_data,
                    timeout=(10, 30),
                    proxies={"http": None, "https": None},
                )

                if response.status_code != 200:
                    print(f"[ERROR] 请求失败，状态码: {response.status_code}")
                    break

                result = response.json()
                current_page_data = result.get("result", {}).get("data", [])

                if not current_page_data:
                    print(f"[INFO] 第 {page_index + 1} 页没有数据，获取完成")
                    break

                all_data.extend(current_page_data)
                print(f"[INFO] 第 {page_index + 1} 页获取 {len(current_page_data)} 条数据，累计 {len(all_data)} 条")

                # 随机延迟避免频繁请求
                delay = random.uniform(1.2, 4.0)
                time.sleep(delay)
                page_index += 1

        except Exception as e:
            print(f"[ERROR] 数据获取过程中发生错误: {e}")
        finally:
            session.close()

        print(f"[INFO] 数据获取完成，总共获取 {len(all_data)} 条数据")
        return all_data

    def analyze_data(self, data: List[Dict[str, Any]]) -> PurchaseDataSummary:
        """分析采购数据 - 以供应商为维度，详细记录货品信息
        
        Args:
            data: 采购明细数据列表
            
        Returns:
            数据汇总分析结果
        """
        if not data:
            return PurchaseDataSummary(
                total_records=0, total_amount=0.0, total_quantity=0.0,
                vendor_count=0, goods_count=0, date_range=("", ""),
                goods_details=[], purchaser_details=[], vendor_details={}
            )

        # 基础统计
        total_records = len(data)
        total_amount = sum(float(item.get('payableAmount', 0) or 0) for item in data)
        total_quantity = sum(float(item.get('quantity', 0) or 0) for item in data)

        # 供应商和商品统计
        vendors = set(item.get('vendId') for item in data if item.get('vendId'))
        goods = set(item.get('goodsNo') for item in data if item.get('goodsNo'))

        # 日期范围
        dates = [item.get('trDate') for item in data if item.get('trDate')]
        date_range = (min(dates) if dates else "", max(dates) if dates else "")

        # 供应商详细分析 - 主要维度
        vendor_details = {}

        for item in data:
            vend_id = item.get('vendId')
            vend_name = item.get('vendName', '')
            amount = float(item.get('payableAmount', 0) or 0)
            quantity = float(item.get('quantity', 0) or 0)
            goods_no = item.get('goodsNo', '')
            goods_name = item.get('goodsName', '')
            sku_name = item.get('skuName', '')
            tax_price = float(item.get('taxPrice', 0) or 0)
            no_tax_price = float(item.get('noTaxPrice', 0) or 0)
            no_tax_amount = float(item.get('noTaxAmount', 0) or 0)
            tax_amount = float(item.get('taxAmount', 0) or 0)
            unit_name = item.get('unitName', '')
            brand_name = item.get('brandName', '')
            cate_name = item.get('cateName', '')
            tr_date = item.get('trDate', '')
            order_date = item.get('orderDate', '')
            rec_date = item.get('recDate', '')
            busi_name = item.get('busiName', '')  # 采购员姓名
            order_num = item.get('orderNum', '')
            goods_doc_no = item.get('goodsdocNo', '')
            warehouse_name = item.get('warehouseName', '')
            batch_no = item.get('batchNo', '')
            serial_no = item.get('serialNo', '')
            sku_barcode = item.get('skuBarcode', '')
            currency_name = item.get('currencyName', '')
            currency_rate = float(item.get('currencyRate', 1) or 1)
            sett_status = item.get('settStatus', '')
            paid_status = item.get('paidStatus', '')
            is_certified = item.get('isCertified', '')
            inout_type = item.get('inouttype', '')
            comment = item.get('comment', '')
            row_remark = item.get('rowRemark', '')
            inout_memo = item.get('inOutMemo', '')
            order_memo = item.get('orderMemo', '')
            order_detail_remark = item.get('orderDetailRemark', '')

            # 如果供应商不存在，初始化
            if vend_id not in vendor_details:
                vendor_details[vend_id] = {
                    'vendorId': vend_id,
                    'vendorName': vend_name,
                    'totalAmount': 0.0,
                    'totalQuantity': 0.0,
                    'totalNoTaxAmount': 0.0,
                    'totalTaxAmount': 0.0,
                    'recordCount': 0,
                    'goodsCount': 0,
                    'purchaserCount': 0,
                    'warehouseCount': 0,
                    'goods': {},  # 货品详情字典
                    'purchasers': set(),  # 采购员集合
                    'warehouses': set(),  # 仓库集合
                    'currencies': set(),  # 币种集合
                    'categories': set(),  # 分类集合
                    'brands': set(),  # 品牌集合
                    'dateRange': [tr_date, tr_date],  # 日期范围
                    'allTransactions': []  # 所有交易记录
                }

            vendor_detail = vendor_details[vend_id]

            # 更新供应商汇总信息
            vendor_detail['totalAmount'] += amount
            vendor_detail['totalQuantity'] += quantity
            vendor_detail['totalNoTaxAmount'] += no_tax_amount
            vendor_detail['totalTaxAmount'] += tax_amount
            vendor_detail['recordCount'] += 1
            vendor_detail['purchasers'].add(busi_name) if busi_name else None
            vendor_detail['warehouses'].add(warehouse_name) if warehouse_name else None
            vendor_detail['currencies'].add(currency_name) if currency_name else None
            vendor_detail['categories'].add(cate_name) if cate_name else None
            vendor_detail['brands'].add(brand_name) if brand_name else None

            # 更新日期范围
            if tr_date:
                if tr_date < vendor_detail['dateRange'][0]:
                    vendor_detail['dateRange'][0] = tr_date
                if tr_date > vendor_detail['dateRange'][1]:
                    vendor_detail['dateRange'][1] = tr_date

            # 货品详细信息
            goods_key = f"{goods_no}_{sku_name}" if sku_name else goods_no
            if goods_key not in vendor_detail['goods']:
                vendor_detail['goods'][goods_key] = {
                    'goodsNo': goods_no,
                    'goodsName': goods_name,
                    'skuName': sku_name,
                    'skuBarcode': sku_barcode,
                    'brandName': brand_name,
                    'cateName': cate_name,
                    'unitName': unit_name,
                    'totalQuantity': 0.0,
                    'totalAmount': 0.0,
                    'totalNoTaxAmount': 0.0,
                    'totalTaxAmount': 0.0,
                    'avgTaxPrice': 0.0,
                    'avgNoTaxPrice': 0.0,
                    'recordCount': 0,
                    'purchasers': set(),  # 采购员集合
                    'warehouses': set(),  # 仓库集合
                    'currencies': set(),  # 币种集合
                    'batchNumbers': set(),  # 批次号集合
                    'serialNumbers': set(),  # 序列号集合
                    'dateRange': [tr_date, tr_date],  # 日期范围
                    'priceHistory': [],  # 价格历史
                    'transactions': []  # 交易记录
                }

            goods_detail = vendor_detail['goods'][goods_key]

            # 更新货品统计
            goods_detail['totalQuantity'] += quantity
            goods_detail['totalAmount'] += amount
            goods_detail['totalNoTaxAmount'] += no_tax_amount
            goods_detail['totalTaxAmount'] += tax_amount
            goods_detail['recordCount'] += 1
            goods_detail['purchasers'].add(busi_name) if busi_name else None
            goods_detail['warehouses'].add(warehouse_name) if warehouse_name else None
            goods_detail['currencies'].add(currency_name) if currency_name else None
            goods_detail['batchNumbers'].add(batch_no) if batch_no else None
            goods_detail['serialNumbers'].add(serial_no) if serial_no else None

            # 更新货品日期范围
            if tr_date:
                if tr_date < goods_detail['dateRange'][0]:
                    goods_detail['dateRange'][0] = tr_date
                if tr_date > goods_detail['dateRange'][1]:
                    goods_detail['dateRange'][1] = tr_date

            # 记录价格历史
            if tax_price > 0:
                goods_detail['priceHistory'].append({
                    'date': tr_date,
                    'taxPrice': tax_price,
                    'noTaxPrice': no_tax_price,
                    'quantity': quantity,
                    'orderNum': order_num
                })

            # 添加货品交易记录
            goods_transaction = {
                'date': tr_date,
                'orderDate': order_date,
                'recDate': rec_date,
                'orderNum': order_num,
                'goodsdocNo': goods_doc_no,
                'purchaser': busi_name,
                'warehouse': warehouse_name,
                'quantity': quantity,
                'taxPrice': tax_price,
                'noTaxPrice': no_tax_price,
                'amount': amount,
                'noTaxAmount': no_tax_amount,
                'taxAmount': tax_amount,
                'batchNo': batch_no,
                'serialNo': serial_no,
                'currencyName': currency_name,
                'currencyRate': currency_rate,
                'settStatus': sett_status,
                'paidStatus': paid_status,
                'isCertified': is_certified,
                'inoutType': inout_type,
                'comment': comment,
                'rowRemark': row_remark,
                'inoutMemo': inout_memo,
                'orderMemo': order_memo,
                'orderDetailRemark': order_detail_remark
            }
            goods_detail['transactions'].append(goods_transaction)

            # 添加供应商总交易记录
            vendor_transaction = {
                'date': tr_date,
                'orderDate': order_date,
                'recDate': rec_date,
                'goodsNo': goods_no,
                'goodsName': goods_name,
                'skuName': sku_name,
                'skuBarcode': sku_barcode,
                'brandName': brand_name,
                'cateName': cate_name,
                'unitName': unit_name,
                'orderNum': order_num,
                'goodsdocNo': goods_doc_no,
                'purchaser': busi_name,
                'warehouse': warehouse_name,
                'quantity': quantity,
                'taxPrice': tax_price,
                'noTaxPrice': no_tax_price,
                'amount': amount,
                'noTaxAmount': no_tax_amount,
                'taxAmount': tax_amount,
                'batchNo': batch_no,
                'serialNo': serial_no,
                'currencyName': currency_name,
                'currencyRate': currency_rate,
                'settStatus': sett_status,
                'paidStatus': paid_status,
                'isCertified': is_certified,
                'inoutType': inout_type,
                'comment': comment,
                'rowRemark': row_remark,
                'inoutMemo': inout_memo,
                'orderMemo': order_memo,
                'orderDetailRemark': order_detail_remark
            }
            vendor_detail['allTransactions'].append(vendor_transaction)

        # 处理供应商数据
        for vend_id, vendor_detail in vendor_details.items():
            # 计算供应商统计数据
            vendor_detail['goodsCount'] = len(vendor_detail['goods'])
            vendor_detail['purchaserCount'] = len(vendor_detail['purchasers'])
            vendor_detail['warehouseCount'] = len(vendor_detail['warehouses'])
            vendor_detail['avgAmount'] = vendor_detail['totalAmount'] / vendor_detail['recordCount'] if vendor_detail[
                                                                                                            'recordCount'] > 0 else 0
            vendor_detail['avgQuantity'] = vendor_detail['totalQuantity'] / vendor_detail['recordCount'] if \
            vendor_detail['recordCount'] > 0 else 0

            # 转换集合为列表
            vendor_detail['purchaserList'] = list(vendor_detail['purchasers'])
            vendor_detail['warehouseList'] = list(vendor_detail['warehouses'])
            vendor_detail['currencyList'] = list(vendor_detail['currencies'])
            vendor_detail['categoryList'] = list(vendor_detail['categories'])
            vendor_detail['brandList'] = list(vendor_detail['brands'])

            # 删除集合
            del vendor_detail['purchasers']
            del vendor_detail['warehouses']
            del vendor_detail['currencies']
            del vendor_detail['categories']
            del vendor_detail['brands']

            # 处理货品数据
            goods_list = []
            for goods_key, goods_detail in vendor_detail['goods'].items():
                # 计算货品平均价格
                if goods_detail['totalQuantity'] > 0:
                    goods_detail['avgTaxPrice'] = goods_detail['totalAmount'] / goods_detail['totalQuantity']
                    goods_detail['avgNoTaxPrice'] = goods_detail['totalNoTaxAmount'] / goods_detail['totalQuantity']

                # 转换集合为列表
                goods_detail['purchaserList'] = list(goods_detail['purchasers'])
                goods_detail['warehouseList'] = list(goods_detail['warehouses'])
                goods_detail['currencyList'] = list(goods_detail['currencies'])
                goods_detail['batchNumberList'] = list(goods_detail['batchNumbers'])
                goods_detail['serialNumberList'] = list(goods_detail['serialNumbers'])
                goods_detail['purchaserCount'] = len(goods_detail['purchasers'])
                goods_detail['warehouseCount'] = len(goods_detail['warehouses'])
                goods_detail['currencyCount'] = len(goods_detail['currencies'])
                goods_detail['batchCount'] = len(goods_detail['batchNumbers'])
                goods_detail['serialCount'] = len(goods_detail['serialNumbers'])

                # 删除集合
                del goods_detail['purchasers']
                del goods_detail['warehouses']
                del goods_detail['currencies']
                del goods_detail['batchNumbers']
                del goods_detail['serialNumbers']

                # 按日期排序价格历史和交易记录
                goods_detail['priceHistory'] = sorted(
                    goods_detail['priceHistory'],
                    key=lambda x: x['date'],
                    reverse=True
                )

                goods_detail['transactions'] = sorted(
                    goods_detail['transactions'],
                    key=lambda x: x['date'],
                    reverse=True
                )

                goods_list.append(goods_detail)

            # 将货品字典转换为列表（不排序，保持原始顺序）
            vendor_detail['goodsList'] = goods_list
            del vendor_detail['goods']

            # 按日期排序供应商交易记录
            vendor_detail['allTransactions'] = sorted(
                vendor_detail['allTransactions'],
                key=lambda x: x['date'],
                reverse=True
            )

        return PurchaseDataSummary(
            total_records=total_records,
            total_amount=total_amount,
            total_quantity=total_quantity,
            vendor_count=len(vendors),
            goods_count=len(goods),
            date_range=date_range,
            goods_details=[],  # 不再使用货品详情列表
            purchaser_details=[],  # 不再使用采购员详情列表
            vendor_details=vendor_details  # 主要使用供应商详情
        )

    def get_data_summary(self,
                         vendor_types: str = "实销实结,OEM实销实结",
                         save_to_file: bool = False,
                         file_path: str = "purchase_data_summary.json") -> PurchaseDataSummary:
        """获取并分析数据汇总
        
        Args:
            vendor_types: 供应商类型
            save_to_file: 是否保存到文件
            file_path: 保存文件路径
            
        Returns:
            数据汇总分析结果
        """
        # 获取数据
        data = self.fetch_purchase_data(vendor_types)

        # 分析数据
        summary = self.analyze_data(data)

        # 保存到文件
        if save_to_file and data:
            summary_dict = {
                'summary': {
                    'total_records': summary.total_records,
                    'total_amount': summary.total_amount,
                    'total_quantity': summary.total_quantity,
                    'vendor_count': summary.vendor_count,
                    'goods_count': summary.goods_count,
                    'date_range': summary.date_range,
                    'generated_at': datetime.now().isoformat()
                },
                'vendor_details': summary.vendor_details,  # 供应商详情
                'raw_data_sample': data[:50]  # 保存前50条原始数据作为样本
            }

            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(summary_dict, f, ensure_ascii=False, indent=2)
            print(f"[INFO] 数据汇总已保存到: {file_path}")

        return summary

    def print_summary(self, summary: PurchaseDataSummary) -> None:
        """打印数据汇总信息"""
        print("\n" + "=" * 50)
        print("采购出入库数据汇总")
        print("=" * 50)
        print(f"总记录数: {summary.total_records:,}")
        print(f"总金额: ¥{summary.total_amount:,.2f}")
        print(f"总数量: {summary.total_quantity:,.2f}")
        print(f"供应商数量: {summary.vendor_count}")
        print(f"商品数量: {summary.goods_count}")
        print(f"日期范围: {summary.date_range[0]} ~ {summary.date_range[1]}")

        # 显示供应商汇总（按金额排序）
        vendor_list = sorted(
            summary.vendor_details.values(),
            key=lambda x: x['totalAmount'],
            reverse=True
        )

        print("\n供应商汇总（按金额排序）:")
        print("-" * 100)
        print(
            f"{'序号':<4} {'供应商名称':<25} {'总金额':<15} {'总数量':<12} {'交易笔数':<8} {'商品种类':<8} {'采购员数':<8} {'仓库数':<8}")
        print("-" * 100)
        for i, vendor in enumerate(vendor_list, 1):
            vendor_name = vendor['vendorName'][:23] if len(vendor['vendorName']) > 23 else vendor['vendorName']
            print(
                f"{i:<4} {vendor_name:<25} ¥{vendor['totalAmount']:<14,.2f} {vendor['totalQuantity']:<11,.2f} {vendor['recordCount']:<8} {vendor['goodsCount']:<8} {vendor['purchaserCount']:<8} {vendor['warehouseCount']:<8}")

    def print_vendor_details(self, summary: PurchaseDataSummary, top_n: int = None) -> None:
        """打印供应商详细信息
        
        Args:
            summary: 数据汇总对象
            top_n: 显示前N个供应商的详情，None表示显示全部
        """
        if not summary.vendor_details:
            print("\n没有供应商详情数据")
            return

        # 按金额排序供应商
        vendor_list = sorted(
            summary.vendor_details.values(),
            key=lambda x: x['totalAmount'],
            reverse=True
        )

        # 如果指定了top_n，则限制数量，否则显示全部
        display_vendors = vendor_list[:top_n] if top_n else vendor_list

        for vendor in display_vendors:
            print("=" * 90)
            print(f"供应商: {vendor['vendorName']}")
            print(f"供应商ID: {vendor['vendorId']}")
            print(f"供应商货品数量: {vendor['goodsCount']}")
            print("-" * 30)
            print("货品明细:")

            # 显示该供应商的所有货品
            if 'goodsList' in vendor and vendor['goodsList']:
                for goods_info in vendor['goodsList']:
                    print("-" * 30)
                    print(f"货品编号: {goods_info['goodsNo']}")
                    print(f"货品名称: {goods_info['goodsName']}")
                    print(f"规格: {goods_info['skuName'] if goods_info['skuName'] else '无'}")
                    print(f"总入库数量: {goods_info['totalQuantity']}")
                    print(f"含税单价: {goods_info['avgTaxPrice']:.2f}")
                    print(f"总含税金额: {goods_info['totalAmount']:.2f}")
            else:
                print("暂无货品明细数据")

            print("-" * 30)
            print(f"供应商应付总金额: {vendor['totalAmount']:.2f}")
            print()

    def print_goods_details(self, summary: PurchaseDataSummary, vendor_id: str = None, top_n: int = 10) -> None:
        """打印货品详细信息
        
        Args:
            summary: 数据汇总对象
            vendor_id: 指定供应商ID，如果为None则显示所有供应商的货品
            top_n: 显示前N个货品的详情
        """
        if not summary.vendor_details:
            print("\n没有供应商详情数据")
            return

        # 收集所有货品或指定供应商的货品
        all_goods = []
        if vendor_id and vendor_id in summary.vendor_details:
            vendor = summary.vendor_details[vendor_id]
            for goods in vendor['goodsList']:
                goods_with_vendor = goods.copy()
                goods_with_vendor['vendorName'] = vendor['vendorName']
                goods_with_vendor['vendorId'] = vendor['vendorId']
                all_goods.append(goods_with_vendor)
            print(f"\n" + "=" * 120)
            print(f"供应商 {vendor['vendorName']} 的货品详细信息（按金额排序，前{top_n}个）")
        else:
            for vendor in summary.vendor_details.values():
                for goods in vendor['goodsList']:
                    goods_with_vendor = goods.copy()
                    goods_with_vendor['vendorName'] = vendor['vendorName']
                    goods_with_vendor['vendorId'] = vendor['vendorId']
                    all_goods.append(goods_with_vendor)
            print(f"\n" + "=" * 120)
            print(f"所有供应商的货品详细信息（按金额排序，前{top_n}个）")

        print("=" * 120)

        if not all_goods:
            print("\n没有货品详情数据")
            return

        # 按金额排序
        goods_sorted = sorted(
            all_goods,
            key=lambda x: x['totalAmount'],
            reverse=True
        )

        for i, goods in enumerate(goods_sorted[:top_n], 1):
            print(f"\n{i}. 商品: {goods['goodsName']}")
            if goods['skuName'] and goods['skuName'] != goods['goodsName']:
                print(f"   SKU: {goods['skuName']}")
            print(f"   商品编号: {goods['goodsNo']}")
            print(f"   供应商: {goods['vendorName']}")
            print(f"   品牌: {goods['brandName'] or '未知'}")
            print(f"   分类: {goods['cateName'] or '未知'}")
            print(f"   单位: {goods['unitName'] or '未知'}")
            print(f"   总金额: ¥{goods['totalAmount']:,.2f}")
            print(f"   总数量: {goods['totalQuantity']:,.2f}")
            print(f"   平均单价: ¥{goods['avgTaxPrice']:,.2f}")
            print(f"   交易笔数: {goods['recordCount']}")
            print(f"   采购员数量: {goods['purchaserCount']}")
            print(f"   仓库数量: {goods['warehouseCount']}")
            print(f"   日期范围: {goods['dateRange'][0]} ~ {goods['dateRange'][1]}")

            # 显示采购员列表
            if goods['purchaserList']:
                purchaser_names = [p for p in goods['purchaserList'] if p]
                if purchaser_names:
                    print(f"   采购员: {', '.join(purchaser_names[:5])}")
                    if len(purchaser_names) > 5:
                        print(f"          ... 还有{len(purchaser_names) - 5}个采购员")

            # 显示最近的交易记录（最多5条）
            if goods['transactions']:
                print(f"\n   最近交易记录:")
                print(f"   {'-' * 90}")
                print(f"   {'日期':<12} {'采购员':<15} {'数量':<10} {'单价':<10} {'金额':<12} {'订单号':<15}")
                print(f"   {'-' * 90}")

                for trans in goods['transactions'][:5]:
                    purchaser = trans['purchaser'][:13] if trans['purchaser'] and len(trans['purchaser']) > 13 else (
                                trans['purchaser'] or '')
                    order_num = trans['orderNum'][:13] if trans['orderNum'] and len(trans['orderNum']) > 13 else (
                                trans['orderNum'] or '')
                    print(
                        f"   {trans['date']:<12} {purchaser:<15} {trans['quantity']:<10.2f} ¥{trans['taxPrice']:<9.2f} ¥{trans['amount']:<11.2f} {order_num:<15}")

                if len(goods['transactions']) > 5:
                    print(f"   ... 还有{len(goods['transactions']) - 5}条交易记录")

            print("\n" + "-" * 120)

    def print_purchaser_details(self, summary: PurchaseDataSummary, top_n: int = 5) -> None:
        """打印采购员详细信息
        
        Args:
            summary: 数据汇总对象
            top_n: 显示前N个采购员的详情
        """
        if not summary.purchaser_details:
            print("\n没有采购员详情数据")
            return

        print(f"\n" + "=" * 100)
        print(f"前{top_n}个采购员详细信息（按金额排序）")
        print("=" * 100)

        for i, purchaser in enumerate(summary.purchaser_details[:top_n], 1):
            print(f"\n{i}. 采购员: {purchaser['purchaserName']}")
            print(f"   总金额: ¥{purchaser['totalAmount']:,.2f}")
            print(f"   总数量: {purchaser['totalQuantity']:,.2f}")
            print(f"   交易笔数: {purchaser['recordCount']}")
            print(f"   商品种类: {purchaser['goodsCount']}")
            print(f"   供应商数量: {purchaser['vendorCount']}")

            # 显示主要供应商
            if purchaser['vendorList']:
                vendor_names = [v.split(':')[1] if ':' in v else v for v in purchaser['vendorList'][:5]]
                print(f"   主要供应商: {', '.join(vendor_names)}")
                if len(purchaser['vendorList']) > 5:
                    print(f"              ... 还有{len(purchaser['vendorList']) - 5}个供应商")

            # 显示最近的交易记录（最多10条）
            if purchaser['transactions']:
                print(f"\n   最近交易记录:")
                print(f"   {'-' * 100}")
                print(f"   {'日期':<12} {'商品名称':<25} {'供应商':<20} {'数量':<10} {'金额':<12}")
                print(f"   {'-' * 100}")

                for trans in purchaser['transactions'][:10]:
                    goods_name = trans['goodsName'][:23] if trans['goodsName'] and len(trans['goodsName']) > 23 else (
                                trans['goodsName'] or '')
                    vendor_name = trans['vendorName'][:18] if trans['vendorName'] and len(
                        trans['vendorName']) > 18 else (trans['vendorName'] or '')
                    print(
                        f"   {trans['date']:<12} {goods_name:<25} {vendor_name:<20} {trans['quantity']:<10.2f} ¥{trans['amount']:<11.2f}")

                if len(purchaser['transactions']) > 10:
                    print(f"   ... 还有{len(purchaser['transactions']) - 10}条交易记录")

            print("\n" + "-" * 100)

    def save_goods_data_to_db(self, summary: PurchaseDataSummary) -> bool:
        """将货品数据保存到dz_real_sales_detail表
        
        Args:
            summary: 数据汇总结果
            
        Returns:
            bool: 保存是否成功
        """
        if not summary.vendor_details:
            print("[WARNING] 没有供应商数据需要保存")
            return False

        connection = None
        try:
            connection = DB()
            cursor = connection.cursor()

            print("[INFO] 开始保存货品数据到dz_real_sales_detail表...")

            # 统计需要更新的货品数量
            total_goods = 0
            for vendor_detail in summary.vendor_details.values():
                total_goods += len(vendor_detail.get('goodsList', []))

            print(f"[INFO] 总共需要更新 {total_goods} 个货品的入库数据")

            updated_count = 0
            skipped_count = 0

            # 遍历所有供应商的货品数据
            for vendor_detail in summary.vendor_details.values():
                vendor_id = vendor_detail.get('vendorId')
                vendor_name = vendor_detail.get('vendorName', '')
                goods_list = vendor_detail.get('goodsList', [])

                for goods in goods_list:
                    goods_no = goods.get('goodsNo')
                    total_quantity = goods.get('totalQuantity', 0)
                    total_amount = goods.get('totalAmount', 0)

                    if not goods_no:
                        print(f"[WARNING] 跳过没有货品编号的记录")
                        skipped_count += 1
                        continue

                    try:
                        # 更新dz_real_sales_detail表中的goodsQtyIn和goodsQtyInAmt字段
                        update_sql = """
                        UPDATE dz_real_sales_detail 
                        SET goodsQtyIn = %s, goodsQtyInAmt = %s
                        WHERE goods_no = %s
                        """

                        cursor.execute(update_sql, (total_quantity, total_amount, goods_no))

                        # 检查是否有记录被更新
                        if cursor.rowcount > 0:
                            updated_count += 1
                            if updated_count % 100 == 0:
                                print(f"[INFO] 已更新 {updated_count} 个货品的入库数据...")
                        else:
                            print(f"[WARNING] 货品编号 {goods_no} 在dz_real_sales_detail表中未找到对应记录")
                            skipped_count += 1

                    except Exception as e:
                        print(f"[ERROR] 更新货品 {goods_no} 时发生错误: {e}")
                        skipped_count += 1
                        continue

            # 提交事务
            connection.commit()

            print(f"[INFO] 货品入库数据保存完成!")
            print(f"[INFO] 成功更新: {updated_count} 个货品")
            print(f"[INFO] 跳过记录: {skipped_count} 个货品")

            return True

        except Exception as e:
            print(f"[ERROR] 保存货品数据到数据库时发生错误: {e}")
            if connection:
                connection.rollback()
            return False

        finally:
            if connection:
                connection.close()


# 使用示例函数
def main():
    """主函数示例"""
    analyzer = RealSalesDataAnalyzer()

    try:
        # 获取并分析数据
        summary = analyzer.get_data_summary(
            vendor_types="实销实结,OEM实销实结",
            save_to_file=True,
            # file_path="purchase_analysis_result.json"
        )

        # 打印汇总信息
        analyzer.print_summary(summary)

        # 打印全部供应商详情
        analyzer.print_vendor_details(summary)

        # 打印货品详情
        # analyzer.print_goods_details(summary, top_n=1000)

        # 保存货品数据到数据库
        analyzer.save_goods_data_to_db(summary)

        return summary

    except Exception as e:
        print(f"[ERROR] 执行过程中发生错误: {e}")
        return None


if __name__ == '__main__':
    main()
